package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出所有分类，以及子分类，以树形结构组装
     *
     * @return 所有分类，以及子分类，以树形结构组装的数据
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类数据
        List<CategoryEntity> allCategoryEntityList = baseMapper.selectList(null);

        // 2.组装成树形结构
        List<CategoryEntity> level1Menus = allCategoryEntityList.stream()
                // 过滤父分类为0的为1级分类
                .filter(item -> item.getParentCid() == 0)
                // 对每个1级分类setChildren操作
                .peek(item -> item.setChildren(getChildren(item, allCategoryEntityList)))
                // 对所有1级分类排序，规避NullPointerException
                .sorted(Comparator.comparingInt(item -> (item.getSort() == null ? 0 : item.getSort())))
                .collect(Collectors.toList());

        return level1Menus;
    }

    /**
     * 删除未被别的地方引用的菜单id列表
     *
     * @param catIds 要删除的菜单id列表
     */
    @Override
    public void removeMenuByIds(List<Long> catIds) {
        // TODO 检查当前删除的菜单，是否被别的地方引用

        // 逻辑删除
        baseMapper.deleteBatchIds(catIds);
    }

    /**
     * 根据分类id查出完整路径
     *
     * @param catelogId 分类id
     * @return [父id, 子id]
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        while (catelogId != 0) {
            paths.add(catelogId);
            CategoryEntity categoryEntity = this.getById(catelogId);
            catelogId = categoryEntity.getParentCid();
        }
        Collections.reverse(paths);
        return paths.toArray(new Long[0]);
    }

    /**
     * 更新分类数据时,同步更新关联表的数据
     *
     * @param category 分类
     */
    // 删除缓存
//    @CacheEvict(value = {"category"}, key = "'getLevel1Categorys'")
    // 批量删除缓存
//    @Caching(evict = {
//            @CacheEvict(value = {"category"}, key = "'getLevel1Categorys'"),
//            @CacheEvict(value = {"category"}, key = "'getCatalogJson'")
//    })
    @CacheEvict(value = "category", allEntries = true)
    @Transactional
    @Override
    public void updateDetailById(CategoryEntity category) {
        baseMapper.updateById(category);
        // 同步更新关联表的数据
        if (StringUtils.isNotEmpty(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
    }

    /**
     * 查询一级分类数据
     *
     * @return 分类数据
     */
    @Cacheable(value = {"category"}, key = "#root.methodName", sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return baseMapper.selectList(
                new QueryWrapper<CategoryEntity>()
                        .eq("parent_cid", 0));
    }

    /**
     * 从spring cache查出所有分类渲染数据
     *
     * @return 分类渲染数据
     */
    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        return getCatalogJsonFromDB();
    }

    /**
     * 从redis查出所有分类渲染数据
     *
     * @return 分类渲染数据
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromRedis() {
        Map<String, List<Catelog2Vo>> data;

        // 从redis中获取数据
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isNotBlank(catalogJSON)) {
            data = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
        } else {
            // DB数据存入redis
            data = getCatalogJsonFromDB();
            String mapJson = JSON.toJSONString(data);
            redisTemplate.opsForValue().set("catalogJSON", mapJson, 1, TimeUnit.DAYS);
        }
        return data;

    }

    /**
     * 从DB中查出所有分类渲染数据
     *
     * @return 分类渲染数据
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDB() {

        /*
          将数据库的多次查询变成一次
         */
        List<CategoryEntity> allCategoryList = baseMapper.selectList(null);

        // 查出所有1级分类
        List<CategoryEntity> level1CategoryList = getCategoryByParentCid(allCategoryList, 0L);

        // 封装1级分类数据
        Map<String, List<Catelog2Vo>> map = level1CategoryList.stream()
                .collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                    // 查询一级分类的二级分类
                    List<CategoryEntity> level2CategoryList = getCategoryByParentCid(allCategoryList, v.getCatId());

                    // 封装2级分类数据
                    List<Catelog2Vo> catelog2VoList = level2CategoryList.stream()
                            .map(entity -> {
                                Catelog2Vo vo = new Catelog2Vo();
                                vo.setId(entity.getCatId().toString());
                                vo.setCatalog1Id(v.getCatId().toString());
                                vo.setName(entity.getName());

                                // 封装3级分类数据
                                List<CategoryEntity> level3CategoryList = getCategoryByParentCid(allCategoryList, entity.getCatId());
                                List<Catelog2Vo.Catalog3Vo> catalog3VoList = level3CategoryList.stream().map(item -> {
                                    Catelog2Vo.Catalog3Vo catalog3Vo = new Catelog2Vo.Catalog3Vo();
                                    catalog3Vo.setId(item.getCatId().toString());
                                    catalog3Vo.setName(item.getName());
                                    catalog3Vo.setCatalog2Id(entity.getCatId().toString());
                                    return catalog3Vo;
                                }).collect(Collectors.toList());
                                vo.setCatalog3List(catalog3VoList);
                                return vo;
                            }).collect(Collectors.toList());

                    return catelog2VoList;
                }));

        return map;
    }

    /**
     * 获取指定父分类id的分类列表
     *
     * @param allCategoryList 所有分类列表
     * @param parentCid       父分类id
     * @return 子分类列表
     */
    private List<CategoryEntity> getCategoryByParentCid(List<CategoryEntity> allCategoryList, Long parentCid) {
        if (parentCid == null) {
            throw new IllegalArgumentException("parentCid不能为空");
        }
        return allCategoryList.stream()
                .filter(item -> parentCid.equals(item.getParentCid()))
                .collect(Collectors.toList());
    }

    /**
     * 获取所有分类列表中当前分类的子分类
     *
     * @param currentCategoryEntity 当前分类
     * @param allCategoryEntityList 所有分类列表
     * @return 当前分类的子分类
     */
    private List<CategoryEntity> getChildren(CategoryEntity currentCategoryEntity, List<CategoryEntity> allCategoryEntityList) {
        List<CategoryEntity> children = allCategoryEntityList.stream()
                // 过滤父分类id为当前分类id的分类
                .filter(item -> currentCategoryEntity.getCatId().equals(item.getParentCid()))
                // 对这些子分类进行setChildren操作
                .peek(item -> item.setChildren(getChildren(item, allCategoryEntityList)))
                // 对所有当前分类的子分类排序，规避NullPointerException
                .sorted(Comparator.comparingInt(item -> (item.getSort() == null ? 0 : item.getSort())))
                .collect(Collectors.toList());

        return children;
    }

}